package com.star95.shirologin.controller;

import com.star95.shirologin.common.constants.CommonConstants;
import com.star95.shirologin.common.util.JwtUtil;
import com.star95.shirologin.common.util.RedisUtil;
import com.star95.shirologin.common.util.UserUtil;
import com.star95.shirologin.dto.CustomerUserDto;
import com.star95.shirologin.dto.OperatorUserDto;
import com.star95.shirologin.dto.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 运营端接口
 */
@Slf4j
@RestController
@RequestMapping("/operator")
@Api(tags = "运营端接口")
public class OperatorController {

    @Autowired
    private RedisUtil redisUtil;

    @ApiOperation("登录接口")
    @PostMapping("/login")
    public Result<OperatorUserDto> login(@Validated @RequestBody OperatorUserDto operatorUserDto) {
        log.info("运营人员登录请求参数，operatorUserDto:{}", operatorUserDto);
        //1. 校验用户是否有效
        OperatorUserDto operatorUserDto1 = UserUtil.operatorUserDtoMap.get(operatorUserDto.getOperatorAccount());
        if (Objects.isNull(operatorUserDto1)) {
            log.info("用户登录失败，用户不存在！");
            return Result.error("用户不存在");
        }
        //2. 校验用户名或密码是否正确
        if (!operatorUserDto1.getPassword().equals(operatorUserDto.getPassword())) {
            log.info("密码不正确，operatorAccount:{}", operatorUserDto1.getOperatorAccount());
            return Result.error("用户名或密码错误");
        }
        //用户登录信息
        log.info("用户账号: {},登录成功！", operatorUserDto1.getOperatorAccount());
        String username = operatorUserDto1.getOperatorAccount();
        String syspassword = operatorUserDto1.getPassword();
        //1.生成token
        String token = JwtUtil.sign(username, syspassword);
        // 设置token缓存有效时间
        redisUtil.set(CommonConstants.PREFIX_USER_TOKEN + token, token, TimeUnit.SECONDS, JwtUtil.EXPIRE_TIME * 2);
        operatorUserDto1.setToken(token);
        return Result.ok(operatorUserDto1);
    }

    @ApiOperation("查询用户列表接口")
    @PostMapping("/customers")
    public Result<List<CustomerUserDto>> customerList() {
        log.info("请求运营端查询用户列表接口");
        return Result.ok(new ArrayList<>(UserUtil.customerUserDtoMap.values()));
    }
}
